package com.xl.util;

import com.xl.mapper.UserMapper;
import com.xl.model.User;
import com.xl.model.Order;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;

import java.util.List;

public class MyBatisTest {

    @Test
    public void testSelectAllUsers() {
        // SqlSession 是 MyBatis 中用于执行 SQL 操作的接口
        // 创建 SqlSession 对象，自动提交事务
        try (SqlSession session = MyBatisUtil.openSession()) {

            // 从 SqlSession 获取 UserMapper 接口的代理对象（mapper）
            UserMapper mapper = session.getMapper(UserMapper.class);

            // 调用 mapper.selectAllUsers() 查询所有用户，并将结果保存在 users 列表中
            List<User> users = mapper.selectAllUsers();
            if (users != null && !users.isEmpty()) {
                users.forEach(System.out::println);
            } else {
                System.out.println("No users found.");
            }
        }
    }

    @Test
    public void testSelectUserById() {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            User user = mapper.selectUserById(1);
            System.out.println(user);
        }
    }

    @Test
    public void testUpdateUser() {
        try (SqlSession session = MyBatisUtil.openSession(false)) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            User user = new User();
            user.setId(1);
            user.setName("Updated Name");
            user.setAge(35);
            mapper.updateUser(user);
            // 方法涉及数据库修改操作，必须在事务中执行，并通过 session.commit() 提交事务
            // 在手动提交模式下，SqlSession 会延迟提交 SQL 操作，直到调用 commit() 才会提交事务
            session.commit();
        }
    }

    @Test
    public void testSelectOrdersByUserId() {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            List<Order> orders = mapper.selectOrdersByUserId(1);    // 返回List
            if (orders == null || orders.isEmpty()) {
                System.out.println("No orders found for user with ID 1");
            } else {
                orders.forEach(System.out::println);
            }
            System.out.println(orders);

        }
    }
}
